package com.lzjn.code.web.dao;

import com.lzjn.code.common.base.CommonDao;
import com.lzjn.code.common.util.PKUtil;
import com.lzjn.code.web.entity.TableConfig;
import com.lzjn.code.web.entity.TableFieldConfig;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

@Repository
public class TableFieldConfigDao extends CommonDao<TableFieldConfig> {

	public List<TableFieldConfig> getList(String tableId) {

		StringBuilder sql = new StringBuilder();
		sql.append("select id,table_id,field_name,field_type,field_length,description,")
		   .append("property_name,property_type,primary_key,nullable,")
		   .append("list_show,list_sort,list_query,")
		   .append("form_show,component_type,form_valid_type,order_no ")
		   .append("from table_field_config where table_id = ? order by order_no");

		List<Object> params = new ArrayList<>();
		params.add(tableId);

		return query(sql.toString(), params);
	}

	public void batchAdd(TableConfig tableConfig, Connection conn) throws Exception {

		StringBuilder sql = new StringBuilder();
		sql.append("insert into table_field_config(id,table_id,field_name,field_type,field_length,description,")
		   .append("property_name,property_type,primary_key,nullable,")
		   .append("list_show,list_sort,list_query,")
		   .append("form_show,component_type,form_valid_type,order_no) ")
		   .append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

		List<List<Object>> paramcs = new ArrayList<>();

		for(TableFieldConfig field : tableConfig.getFieldConfigs()) {

			List<Object> paramc = new ArrayList<>();
			paramc.add(PKUtil.getUUID());
			paramc.add(tableConfig.getId());
			paramc.add(field.getFieldName());
			paramc.add(field.getFieldType());
			paramc.add(field.getFieldLength() == null ? 0 : field.getFieldLength());
			paramc.add(field.getDescription());
			paramc.add(field.getPropertyName());
			paramc.add(field.getPropertyType());
			paramc.add(field.getPrimaryKey());
			paramc.add(field.getNullable());
			paramc.add(field.getListShow());
			paramc.add(field.getListSort());
			paramc.add(field.getListQuery());
			paramc.add(field.getFormShow());
			paramc.add(field.getComponentType());
			paramc.add(field.getFormValidType());
			paramc.add(field.getOrderNo());

			paramcs.add(paramc);
		}

		executeBatchUpdate(sql.toString(), paramcs, conn);
	}

	public void delete(String tableId, Connection conn) throws Exception {

		String sql = "delete from table_field_config where table_id = ?";

		List<Object> params = new ArrayList<>();
		params.add(tableId);

		executeUpdate(sql, params, conn);
	}

	public void batchDelete(String tableIds, Connection conn) throws Exception {

		tableIds = tableIds.replace(",", "','");

		String sql = "delete from table_field_config where table_id in ('" + tableIds + "')";

		executeUpdate(sql, null, conn);
	}
}
